package com.kexin.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

public class ParamMap {
    public static  Map<String,Object> paramsToMapObject(HttpServletRequest request){
        Enumeration<String> params=request.getParameterNames();
        Map<String,Object> paramMap=new HashMap<>();
        while (params.hasMoreElements()){
            String param=params.nextElement();
            paramMap.put(param,request.getParameter(param));
        }
        return paramMap;
    }
    public static  Map<String,String> paramsToMapString(HttpServletRequest request){
        Enumeration<String> params=request.getParameterNames();
        Map<String,String> paramMap=new HashMap<>();
        while (params.hasMoreElements()){
            String param=params.nextElement();
            paramMap.put(param,request.getParameter(param));
        }
        return paramMap;
    }

    public static<T> T paramsToBean(HttpServletRequest request,Class<T> clazz){
        try {
            Map<String,Object> map = paramsToMapObject(request);
            String jsonStr = JSON.toJSONString(map);
            T bean = JSONObject.parseObject(jsonStr,clazz);
            return bean;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("参数转换失败");
        }
    }

    public static Map<String, Object> beanToMap(Object obj) {
        Map<String, Object> map = new HashMap<>();
        if (obj == null) {
            return map;
        }
        Class clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        try {
            for (Field field : fields) {
                field.setAccessible(true);
                map.put(field.getName(), field.get(obj));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}
